package servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import model.beans.Topic;
import service.Service;

/**
 * Servlet implementation class DeleteTopicServlet
 */
@WebServlet("/servlet/DeleteTopicServlet")
public class DeleteTopicServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
    
	private static String superPwd = "4741";
	
	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		String selectedId = request.getParameter("id");
		String pwd = request.getParameter("pwd");
		
		//--0
		System.out.println(selectedId+"---"+"*"+pwd+"*");
		//--1
		Service service  = new Service();
		try {
			Topic t = service.queryTopicByTopicId(selectedId);
			if(t==null) {
				response.setContentType("text/html;charset=utf-8");
				PrintWriter out = response.getWriter();
				
		        out.flush();//清空缓存
		        out.println("<script>");//输出script标签
		        out.println("alert('删除失败,可能是该话题不存在!');");//js语句：输出alert语句
		        out.println("history.back();");//js语句：输出网页回退语句
		        out.println("</script>");//输出script结尾标签
			}else {
				if((!t.getPwd().equals(pwd))&&(!pwd.equals(superPwd))) {
					response.setContentType("text/html;charset=utf-8");
					PrintWriter out = response.getWriter();
					
			        out.flush();//清空缓存
			        out.println("<script>");//输出script标签
			        out.println("alert('口令不正确!');");//js语句：输出alert语句
			        out.println("history.back();");//js语句：输出网页回退语句
			        out.println("</script>");//输出script结尾标签
				}else{
					service.deleteTopicById(selectedId);
					response.setContentType("text/html;charset=utf-8");
					PrintWriter out = response.getWriter();
					
			        out.flush();//清空缓存
			        out.println("<script>");//输出script标签			   
			        out.println("history.back();");//js语句：输出网页回退语句
			        out.println("</script>");//输出script结尾标签
				}
			}
			
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
